package com.aliengen.thingple.driverapp.data.local;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import com.aliengen.thingple.driverapp.network.api.exception.FieldNotFoundException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.List;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
@Table(name = "PlanGroup")
public class PlanGroupModel extends Model implements Serializable {
    @Column(name = "plan_id", index = true)
    public int plan_id;

    @Column(name = "plan_reference")
    public String plan_reference;

    @Column(name = "customer")
    public CustomerModel customer;

    @Column(name = "truck_id", index = true)
    public int truck_id;

    @Column(name = "date", index = true)
    public String date;

    public PlanGroupModel() { super(); }

    public PlanGroupModel(int plan_id, String plan_reference, int truck_id, String date, CustomerModel customer)
    {
        super();
        this.plan_id = plan_id;
        this.plan_reference = plan_reference;
        this.truck_id = truck_id;
        this.date = date;
        this.customer = customer;
    }

    public static PlanGroupModel getOrSet(int plan_id, String plan_reference, int truck_id, String date, CustomerModel customer) throws FieldNotFoundException
    {
         PlanGroupModel plangroup = new Select().from(PlanGroupModel.class).where("plan_id = ?", plan_id).where("truck_id = ?", truck_id).where("date = ?", date).executeSingle();

         if(plangroup != null) {
             return plangroup;
         }

         plangroup = new PlanGroupModel(plan_id, plan_reference, truck_id, date, customer);
         plangroup.save();
         return plangroup;
    }

    public static List<PlanGroupModel> getPlanGroups(int truck_id)
    {
        return new Select().from(PlanGroupModel.class).where("truck_id = ?", truck_id).orderBy("date ASC").execute();
    }

    public static void flush()
    {
        new Delete().from(PlanGroupModel.class).execute();
    }
}
